

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/favicon.png">
  <link rel="icon" type="image/png" href="/blog/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#fff">
  <meta name="description" content="その時を待つよ">
  <meta name="author" content="Isshiki_Hugh">
  <meta name="keywords" content="">
  <title>algorithm-排序专题 - Isshiki&#39;sBlog</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/blog/lib/hint/hint.min.css" />

  
    
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/atom-one-dark.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_6peoq002giu.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/blog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.0.2"></head>


<body>
  <header style="height: 75vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>Isshiki修のBlog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/blog/img/default.JPG') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-10-17 08:17" pubdate>
      2019年10月17日 早上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      515 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      6
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">algorithm-排序专题</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2 年前
                
              </p>
            
            <div class="markdown-body" id="post-body">
              <h3 id="0-x-前言"><a href="#0-x-前言" class="headerlink" title="[0.x]前言"></a>[0.x]前言</h3><p>本文针对<script type="math/tex">CSP-S_{(初赛)}</script></p>
<p>程序以<script type="math/tex">cpp</script>为例</p>
<p>由于时间关系，并非所有算法都提供了样例代码</p>
<p>参考github项目<a target="_blank" rel="noopener" href="https://github.com/MisterBooo/LeetCodeAnimation"><strong>LeetCodeAnimation</strong></a></p>
<p>本blog中的动图全部引用<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s?__biz=MzUyNjQxNjYyMg==&amp;mid=2247484095&amp;idx=1&amp;sn=174a8b95900448c73507955250b759cc&amp;chksm=fa0e6d3ecd79e428aac5c52d77c335678b583926e3d3c973513c1a8444951f3e03f820375d61&amp;scene=21#wechat_redirect">这里</a></p>
<a id="more"></a>
<h3 id="目录"><a href="#目录" class="headerlink" title="目录"></a>目录</h3><ul>
<li>[0.x]前言</li>
<li>[1.x]十大排序<ul>
<li>[1.0]概述</li>
<li>[1.1]冒泡排序</li>
<li>[1.2]快速排序</li>
<li>[1.3]插入排序</li>
<li>[1.4]希尔排序</li>
<li>[1.5]选择排序</li>
<li>[1.6]堆排序</li>
<li>[1.7]归并排序</li>
<li>[1.8]计数排序</li>
<li>[1.9]桶排序</li>
</ul>
</li>
<li>[2.x]其他排序<ul>
<li>[1.1]地精排序</li>
</ul>
</li>
</ul>
<hr>
<h3 id="1-x-十大排序"><a href="#1-x-十大排序" class="headerlink" title="[1.x]十大排序"></a>[1.x]十大排序</h3><h4 id="1-0-概述"><a href="#1-0-概述" class="headerlink" title="[1.0]概述"></a>[1.0]概述</h4><p>排序，顾名思义，将一组数据按照一定顺序重新排列。很容易看出这是非常常用的东西，因此我们肯定希望更快的实现它。但不同的排序有不同的性质，其中的思想也有很大的学习价值，所以我们要尽数掌握。<del>(其实只是初赛要考？)</del></p>
<p>大的来分，排序分为<strong>内排序</strong>和<strong>外排序</strong>，两者的区别并不是我们学习的重点。我们移步到<strong>内排序</strong>。内排序分为<strong>比较类</strong>和<strong>非比较类</strong>，两者的区别自然是是否需要比较。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/Kk00mt.png" srcset="/blog/img/loading.gif" alt="avatar"></p>
<p>不过论实际码题的时候，使用<code>&lt;algorithm&gt;</code>中的<code>sort()</code>在大部分情况下是够用的(<script type="math/tex">cpp</script>)。(至少在蒟蒻这个水平是完全够用的嘤嘤嘤)</p>
<p>首先在初赛范围内，考察排序算法的<strong>原理</strong>、<strong>时间复杂度</strong>、<strong>稳定性</strong>。首先贴一张全表。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/Kkw4iD.png" srcset="/blog/img/loading.gif" alt="avatar"></p>
<h4 id="1-1-冒泡排序"><a href="#1-1-冒泡排序" class="headerlink" title="[1.1]冒泡排序"></a>[1.1]冒泡排序</h4><p>冒泡排序的名字是其原理的形象比喻。关于冒泡最优情况下为什么是<script type="math/tex">O(n)</script>将在算法示例之后。算法实现如下：</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEq1MQ.gif" srcset="/blog/img/loading.gif" alt=""></p>
<p><strong>算法描述：</strong></p>
<p>1.第<script type="math/tex">i</script>轮，从<script type="math/tex">i</script>位开始，令<script type="math/tex">j=i</script></p>
<p>2.比较<script type="math/tex">j</script>和<script type="math/tex">j+1</script>上的数，并进行有序化(如果需要升序就将小的放在前面，反之把大的放在前面，为保证稳定性相等不变换)</p>
<p>3.不断重复[2]直到<script type="math/tex">j==n</script>返回<script type="math/tex">true</script></p>
<p>4.1.如果<script type="math/tex">i<n</script>，那么<script type="math/tex">i=i+1</script>并返回[1]</p>
<p>4.2.如果<script type="math/tex">i =n</script>，排序结束</p>
<p><strong>算法样例：</strong></p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cin</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>;
<span class="hljs-keyword">int</span> n,a[<span class="hljs-number">1000</span>];
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">swap</span><span class="hljs-params">(<span class="hljs-keyword">int</span> *p,<span class="hljs-keyword">int</span> *q)</span></span>&#123;
    <span class="hljs-keyword">int</span> c = *p; *p = *q , *q = c;
    <span class="hljs-keyword">return</span>;
&#125;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-keyword">int</span> n;
    <span class="hljs-built_in">cin</span> &gt;&gt; n;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++) <span class="hljs-built_in">cin</span> &gt;&gt; a[i];
    <span class="hljs-comment">/*主体开始*/</span>
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n<span class="hljs-number">-1</span>;i++)&#123;
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j = i;j &lt;= n<span class="hljs-number">-1</span>;j++)&#123;
            <span class="hljs-keyword">if</span>(a[j] &gt; a[j + <span class="hljs-number">1</span>]) swap(&amp;a[j] , &amp;a[j + <span class="hljs-number">1</span>]); 
        &#125;
    &#125;
    <span class="hljs-comment">/*主体结束*/</span>
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++)&#123;
        <span class="hljs-built_in">cout</span> &lt;&lt; a[i] &lt;&lt; <span class="hljs-string">&quot; &quot;</span>;
    &#125;
&#125;</code></pre></div>
<p><strong>补充说明：</strong>关于冒泡排序的最优情况问题，我们可以用一个flag标记，如果它在第一次扫描过程中没有交换，显然得到这是一个有序数列。那么就不需要之后的<script type="math/tex">n-2</script>次扫描了</p>
<h4 id="1-2-快速排序"><a href="#1-2-快速排序" class="headerlink" title="[1.2]快速排序"></a>[1.2]快速排序</h4><p>快排是比较常用的排序算法，也是<code>&lt;algorithm&gt;</code>中<code>sort()</code>的原型。算法实现如下：</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEqRJK.gif" srcset="/blog/img/loading.gif" alt=""></p>
<p><strong>算法描述：</strong></p>
<p>1.选择基数作为比较对象。(一般选择最左或最右)</p>
<p>2.令除基数外的最左数下标为<script type="math/tex">l</script>,最右数下标为<script type="math/tex">r</script></p>
<p>3.判断<script type="math/tex">r</script>位数字是否比基数小(升序时)，如果不是，那么<script type="math/tex">r</script>左移</p>
<p>4.判断<script type="math/tex">l</script>位数字是否比基数大(升序时)，如果不是，那么<script type="math/tex">l</script>右移</p>
<p>5.当$l==r$返回<script type="math/tex">true</script>时将<script type="math/tex">i</script>位数和基数交换</p>
<p>6.对<script type="math/tex">1</script>至<script type="math/tex">l-1</script>和<script type="math/tex">r+1</script>至<script type="math/tex">n</script>分别进行[1] (二分过程)</p>
<p><strong>算法样例：</strong></p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cin</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::swap;
<span class="hljs-keyword">int</span> a[<span class="hljs-number">100001</span>],n;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">q_sort</span><span class="hljs-params">(<span class="hljs-keyword">int</span> L,<span class="hljs-keyword">int</span> R)</span></span>&#123;
    <span class="hljs-comment">//默认最左的a[L]为基数 </span>
    <span class="hljs-keyword">if</span>(L &gt; R) <span class="hljs-keyword">return</span>;
    <span class="hljs-keyword">int</span> l,r;
    l = L , r = R;
    <span class="hljs-keyword">while</span>(l != r)&#123;
        <span class="hljs-keyword">while</span>(l &lt; r &amp;&amp; a[r] &gt;= a[L]) r--;
        <span class="hljs-keyword">while</span>(l &lt; r &amp;&amp; a[l] &lt;= a[L]) l++;
        <span class="hljs-keyword">if</span>(l &lt; r) swap(a[l] , a[r]);
    &#125;
    swap(a[l] , a[L]);
    q_sort(L,l<span class="hljs-number">-1</span>);
    q_sort(l+<span class="hljs-number">1</span>,R);
    <span class="hljs-keyword">return</span>;
&#125;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-built_in">cin</span> &gt;&gt; n;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++) <span class="hljs-built_in">cin</span> &gt;&gt; a[i];
    q_sort(<span class="hljs-number">1</span>,n);
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++)&#123;
        <span class="hljs-built_in">cout</span> &lt;&lt; a[i] &lt;&lt;<span class="hljs-string">&quot; &quot;</span>;
    &#125;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
&#125;</code></pre></div>
<h4 id="1-3-插入排序"><a href="#1-3-插入排序" class="headerlink" title="[1.3]插入排序"></a>[1.3]插入排序</h4><p>插入排序首先构造有序数列，然后将无序数列中的元素插入到有序数列中。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEqBM4.gif" srcset="/blog/img/loading.gif" alt=""></p>
<p><strong>算法描述：</strong></p>
<p>1.第<script type="math/tex">i</script>轮，有<script type="math/tex">1</script>~<script type="math/tex">i</script>为有序数列。令<script type="math/tex">j=i+1</script></p>
<p>2.<script type="math/tex">j</script>不断左移，比较<script type="math/tex">j</script>位和<script type="math/tex">i+1</script>位的数的大小，并进行插入操作，返回[1]</p>
<h4 id="1-4-希尔排序"><a href="#1-4-希尔排序" class="headerlink" title="[1.4]希尔排序"></a>[1.4]希尔排序</h4><p>希尔排序十分迷幻，你可以发现它的复杂度十分一枝独<strong>秀</strong></p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEL9wn.gif" srcset="/blog/img/loading.gif" alt=""></p>
<h4 id="1-5-选择排序"><a href="#1-5-选择排序" class="headerlink" title="[1.5]选择排序"></a>[1.5]选择排序</h4><p>选择排序它看起来非常稳定，但其实还是存在问题的，放在最后解释。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEqyZR.gif" srcset="/blog/img/loading.gif" alt=""></p>
<p><strong>算法描述：</strong></p>
<p>1.扫描无序数列，找到【最小/最大】的一个，将它放到无序数列前，有序数列末。</p>
<p>2.重复[1]直到不存在无序数列</p>
<p><strong>算法示例：</strong></p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cin</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::swap;
<span class="hljs-keyword">int</span> n,a[<span class="hljs-number">1000</span>],min;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-built_in">cin</span> &gt;&gt; n;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++) <span class="hljs-built_in">cin</span> &gt;&gt; a[i];
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>;i &lt;= n - <span class="hljs-number">1</span>;i++)&#123;
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j = i + <span class="hljs-number">1</span>;j &lt;= n;j++)
         min = a[i] &lt;= a[j] ? i : j;
        swap(a[min] , a[i]);
    &#125;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++) <span class="hljs-built_in">cout</span> &lt;&lt; a[i] &lt;&lt; <span class="hljs-string">&quot; &quot;</span>;
&#125;</code></pre></div>
<p><strong>补充说明：</strong></p>
<p>确实，乍一看选择排序好像很稳定。但实际上并非如此。</p>
<p>确实，在每一次交换过程中，我们能保证<script type="math/tex">min</script>位上的数和其后的与它等大的数的相对位置不变。<strong>但是</strong>，在你交换的过程中，<strong>和<script type="math/tex">min</script>交换的那个数</strong>的稳定性就被破坏了。什么意思？举个例子：</p>
<p>在无序数列<script type="math/tex">5_A</script>  <script type="math/tex">3_A</script>  <script type="math/tex">5_B</script>  <script type="math/tex">1_A</script>  <script type="math/tex">2_A</script>中，模拟知道我们需要将<script type="math/tex">5_A</script>和<script type="math/tex">1_A</script>交换，于是数列就变成了<script type="math/tex">1_A</script>  <script type="math/tex">3_A</script>  <script type="math/tex">5_B</script>  <script type="math/tex">5_A</script>  <script type="math/tex">2_A</script>，显然，<script type="math/tex">5</script>的稳定性就被破坏了。</p>
<h4 id="1-6-堆排序"><a href="#1-6-堆排序" class="headerlink" title="[1.6]堆排序"></a>[1.6]堆排序</h4><p>堆排利用了【大根堆/小根堆的性质】</p>
<p><strong>大根堆性质：</strong>任何一个非叶节点的值<strong>不小于</strong>其左儿子和右儿子的值</p>
<p>根据该性质，我们可以得到，我们维护的大根堆的根节点是整个数列中最大的。</p>
<p>小根堆反之。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEqDsJ.gif" srcset="/blog/img/loading.gif" alt=""></p>
<p><strong>算法描述：</strong></p>
<p>1.1.将数列中的第一个元素一次推如堆底，并将该数从队列中删除</p>
<p>1.2.依据堆的性质将底部的元素向根部移动，返回[1.1]</p>
<p>1.3.等到全部元素被推入堆中，建堆完成</p>
<p>2.1.输出堆根，然后将堆根删除，将堆底元素直接移动到堆根</p>
<p>2.2.根据堆的性质下移，返回[2.1]</p>
<p>2.3.等到堆为空，则输出完成</p>
<h4 id="1-7-归并排序"><a href="#1-7-归并排序" class="headerlink" title="[1.7]归并排序"></a>[1.7]归并排序</h4><p>归并排序将原数列不断分裂，然后再将有序数列合并。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEq2i6.gif" srcset="/blog/img/loading.gif" alt=""></p>
<p><strong>算法描述：</strong></p>
<p>1.选取目标队列<script type="math/tex">mid</script>，将数列分为两部分，作为新的目标队列</p>
<p>2.当目标队列中元素数量为<script type="math/tex">2</script>或<script type="math/tex">1</script>，或该序列的所有子序列已经被分别有序化时，不断比较两个子序列的首尾，将较小(升序时)的一项推入储存数组，得到储存数组中的有序数列后覆盖原数列。返回[1]</p>
<p><strong>算法示例：</strong></p>
<div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cin</span>;<span class="hljs-keyword">using</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>;
<span class="hljs-keyword">int</span> n,a[<span class="hljs-number">1000</span>],tmp[<span class="hljs-number">1000</span>];
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">merge_sort</span><span class="hljs-params">(<span class="hljs-keyword">int</span> l,<span class="hljs-keyword">int</span> r)</span></span>&#123;
    <span class="hljs-keyword">if</span>(l == r) <span class="hljs-keyword">return</span>;
    <span class="hljs-keyword">int</span> mid = (l + r) &gt;&gt; <span class="hljs-number">1</span>;
    merge_sort(l,mid) , merge_sort(mid+<span class="hljs-number">1</span>,r);
    <span class="hljs-keyword">int</span> i = l , p = l , j = mid + <span class="hljs-number">1</span>;
    <span class="hljs-comment">//归并</span>
    <span class="hljs-keyword">while</span>(i &lt;= mid &amp;&amp; j &lt;= r)&#123;
        <span class="hljs-keyword">if</span>(a[i] &gt; a[j]) tmp[p++] = a[j++];
        <span class="hljs-keyword">else</span> tmp[p++] = a[i++];
    &#125;
    <span class="hljs-comment">//处理奇数元素情况下的多余元素</span>
    <span class="hljs-keyword">while</span>(i &lt;= mid) tmp[p++] = a[i++];
    <span class="hljs-keyword">while</span>(j &lt;= r) tmp[p++] = a[j++];
    <span class="hljs-comment">//覆盖原数列</span>
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = l;i &lt;= r;i++)&#123;
        a[i] = tmp[i];
    &#125;
&#125;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-built_in">cin</span> &gt;&gt; n;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++) <span class="hljs-built_in">cin</span> &gt;&gt; a[i];
    merge_sort(<span class="hljs-number">1</span>,n);
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;i &lt;= n;i++) <span class="hljs-built_in">cout</span> &lt;&lt; a[i] &lt;&lt; <span class="hljs-string">&quot; &quot;</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
&#125;</code></pre></div>
<h4 id="1-8-计数排序"><a href="#1-8-计数排序" class="headerlink" title="[1.8]计数排序"></a>[1.8]计数排序</h4><p>计数排序其实是朴素桶排的优化版本<del>(反正浪费空间的德行是一样的)</del>，区别就是选取了起点和终点，适合数据偏差值较小，但都偏大的数据范围。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEqrL9.gif" srcset="/blog/img/loading.gif" alt=""></p>
<h4 id="1-9-桶排序"><a href="#1-9-桶排序" class="headerlink" title="[1.9]桶排序"></a>[1.9]桶排序</h4><p>没写这篇博客之前我都不知道桶排还可以这样玩(妙得一匹啊)</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_gif/D67peceibeISwc3aGibUlvZ0XqVnbWtBRia0umOurgFRv8ESYzcK6bXknufLgJGLaiaTrDTXUk09R6ia2DhbCPAJx0A/640?wx_fmt=gif&amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1" srcset="/blog/img/loading.gif" alt=""></p>
<h4 id="1-10-基数排序"><a href="#1-10-基数排序" class="headerlink" title="[1.10]基数排序"></a>[1.10]基数排序</h4><p>一个原理非常神奇的排序方法，按照每一位的大小进行排序，用队列维护先进先出的性质就可以保证稳定性。</p>
<p><img src="https://s2.ax1x.com/2019/10/17/KEqcIx.gif" srcset="/blog/img/loading.gif" alt=""></p>
<h3 id="2-x-其他排序"><a href="#2-x-其他排序" class="headerlink" title="[2.x]其他排序"></a>[2.x]其他排序</h3><p>此处为考点外的内容，用来补充说明<del>课外</del>知识</p>
<h4 id="2-1-地精排序"><a href="#2-1-地精排序" class="headerlink" title="[2.1]地精排序"></a>[2.1]地精排序</h4><p><strong><a target="_blank" rel="noopener" href="https://www.zhihu.com/question/26934313/answer/573037708">传送门</a></strong></p>
<h4 id="2-2-Bogo-Sort-猴子排序"><a href="#2-2-Bogo-Sort-猴子排序" class="headerlink" title="[2.2] Bogo Sort / 猴子排序"></a>[2.2] Bogo Sort / 猴子排序</h4><div class="hljs"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;algorithm&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> rep(i,a,b) for(register long long i = (a);i &lt;= (b);++i)</span>
<span class="hljs-keyword">int</span> n,a[<span class="hljs-number">1000010</span>];
<span class="hljs-function"><span class="hljs-keyword">inline</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">judge</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-keyword">bool</span> flag = <span class="hljs-literal">true</span>;
    rep(i,<span class="hljs-number">2</span>,n) <span class="hljs-keyword">if</span>(a[i - <span class="hljs-number">1</span>] &gt; a[i])&#123;flag = <span class="hljs-literal">false</span>; <span class="hljs-keyword">break</span>;&#125;
    <span class="hljs-keyword">return</span> flag;
&#125;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cin</span> &gt;&gt; n;
    rep(i,<span class="hljs-number">1</span>,n) <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cin</span> &gt;&gt; a[i];
    <span class="hljs-keyword">while</span>(!judge()) <span class="hljs-built_in">std</span>::random_shuffle(a + <span class="hljs-number">1</span>,a + n + <span class="hljs-number">1</span>);
    rep(i,<span class="hljs-number">1</span>,n) <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; a[i] &lt;&lt; <span class="hljs-string">&quot; &quot;</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
&#125;</code></pre></div>
<link rel="stylesheet" href="/blog/css/spoiler.css" type="text/css"><script src="/blog/js/spoiler.js" type="text/javascript" async></script>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/blog/categories/%E7%AE%97%E6%B3%95/">算法</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E7%AE%97%E6%B3%95/">算法</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E4%BF%A1%E5%A5%A5/">信奥</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E4%B8%93%E9%A2%98/">专题</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E6%8E%92%E5%BA%8F/">排序</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">未经允许禁止用于商业用途，转载请标注出处和作者！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2019/10/25/artHPQY/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">anime-《花牌情缘》观后感<少女番外皮的硬核花(歌)牌运动番></span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2019/10/17/algTK/">
                        <span class="hidden-mobile">algorithm-历届程序填空专题</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                <!-- 来必力City版安装代码 -->
<div id="lv-container" data-id="city" data-uid="MTAyMC80ODI4NS8yNDc3OQ==">
  <script type="text/javascript">
     (function(d, s) {
         var j, e = d.getElementsByTagName(s)[0];
  
         if (typeof LivereTower === 'function') { return; }
  
         j = d.createElement(s);
         j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
         j.async = true;
  
         e.parentNode.insertBefore(j, e);
     })(document, 'script');
  </script>
  <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
  </div>
  <!-- City版安装代码已完成 -->
              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->

  <div class="col-lg-7 mx-auto nopadding-md">
    <div class="container custom post-content mx-auto">
      <p><center><b>(っ*´Д`)っ㊖ <font color="darkblue">  疯 狂 暗 示  </font>(っ*´Д`)っ㊖</b></center></p><center><img src="https://pic.downk.cc/item/5f3bd3b414195aa59408fb13.png" srcset="/blog/img/loading.gif" width="50%" height="50%"/></center>
    </div>
  </div>


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  
    <!-- APlayer 音乐播放器 -->
    <div id="aplayer"></div>
    <script defer src="https://cdn.staticfile.org/aplayer/1.10.1/APlayer.min.js" ></script>
<link  rel="stylesheet" href="https://cdn.staticfile.org/aplayer/1.10.1/APlayer.min.css" />
<script type="text/javascript">
  var oldLoadAp = window.onload;
  window.onload = function () {
    oldLoadAp && oldLoadAp();

    new APlayer({
      container: document.getElementById('aplayer'),
      fixed: true,
      autoplay: 'false' === 'true',
      loop: 'all',
      order: 'random',
      theme: '#708090',
      preload: 'none',
      audio: [{"name":"SLEEPWALK","artist":"冰镇豆沙君","url":"http://music.163.com/song/media/outer/url?id=1417007045.mp3","cover":"/img/cover.jpg"},{"name":"雨き声残响","artist":"冰镇豆沙君","url":"http://music.163.com/song/media/outer/url?id=1318309030.mp3","cover":"/img/cover.jpg"},{"name":"春を告げる","artist":"茶玖","url":"http://music.163.com/song/media/outer/url?id=1460240705.mp3","cover":"/img/cover.jpg"},{"name":"ベクターフィッシュ","artist":"茶玖","url":"http://music.163.com/song/media/outer/url?id=1445572300.mp3","cover":"/img/cover.jpg"},{"name":"红莲华","artist":"噢耶","url":"http://music.163.com/song/media/outer/url?id=1397590357.mp3","cover":"/img/cover.jpg"},{"name":"横竖撇点折","artist":"噢耶","url":"http://music.163.com/song/media/outer/url?id=1421414775.mp3","cover":"/img/cover.jpg"},{"name":"たぶん","artist":"真央","url":"http://music.163.com/song/media/outer/url?id=1464762744.mp3","cover":"/img/cover.jpg"},{"name":"夜に駆ける","artist":"真央","url":"http://music.163.com/song/media/outer/url?id=1461930738.mp3","cover":"/img/cover.jpg"},{"name":"Alice","artist":"yakuri","url":"http://music.163.com/song/media/outer/url?id=1431092750.mp3","cover":"/img/cover.jpg"},{"name":"起风了","artist":"yakuri","url":"http://music.163.com/song/media/outer/url?id=1367440424.mp3","cover":"/img/cover.jpg"}]
    });
  }
</script>

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/debouncer.js" ></script>
<script  src="/blog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/blog/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 6,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "algorithm-排序专题&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 50,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>





  <script  src="/blog/js/local-search.js" ></script>
  <script>
    var path = "/blog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  



  
  
    <script type="text/javascript">
      //定义获取词语下标
      var a_idx = 0;
      jQuery(document).ready(function ($) {
        //点击body时触发事件
        $("body").click(function (e) {
          //需要显示的词语
          var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
          //设置词语给span标签
          var $i = $("<span/>").text(a[a_idx]);
          //下标等于原来下标+1  余 词语总数
          a_idx = (a_idx + 1) % a.length;
          //获取鼠标指针的位置，分别相对于文档的左和右边缘。
          //获取x和y的指针坐标
          var x = e.pageX, y = e.pageY;
          //在鼠标的指针的位置给$i定义的span标签添加css样式
          $i.css({
            "z-index": 999,
            "top": y - 20,
            "left": x,
            "position": "absolute",
            "font-weight": "bold",
            "color": rand_color()
          });
          // 随机颜色
          function rand_color() {
            return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
          }
          //在body添加这个标签
          $("body").append($i);
          //animate() 方法执行 CSS 属性集的自定义动画。
          //该方法通过CSS样式将元素从一个状态改变为另一个状态。CSS属性值是逐渐改变的，这样就可以创建动画效果。
          //详情请看http://www.w3school.com.cn/jquery/effect_animate.asp
          $i.animate({
            //将原来的位置向上移动180
            "top": y - 180,
            "opacity": 0
            //1500动画的速度
          }, 1500, function () {
            //时间到了自动删除
            $i.remove();
          });
        });
      })
      ;
    </script>
  














<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.618,"jsonPath":"/blog/live2dw/assets/assets/hijiki.model.json"},"display":{"superSample":1,"width":150,"height":300,"position":"right","hOffset":0,"vOffset":-20},"mobile":{"show":true,"scale":1},"react":{"opacityDefault":0.7,"opacityOnHover":0.2},"log":false});</script></body>
</html>
